<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="tabs">

			<view class="tab" :class="{ active: activeTab === '全部' }" @click="setActiveTab('全部')">全部</view>
			<view class="tab" :class="{ active: activeTab === '待签署' }" @click="setActiveTab('待签署')">待签署</view>
			<view class="tab" :class="{ active: activeTab === '待支付' }" @click="setActiveTab('待支付')">待支付</view>
			<view class="tab" :class="{ active: activeTab === '待出行' }" @click="setActiveTab('待出行')">待出行</view>
			<view class="tab" :class="{ active: activeTab === '已完成' }" @click="setActiveTab('已完成')">已完成</view>
		</view>
		<!-- 内容区域 -->
		<scroll-view class="order-list" scroll-y>
			<view v-for="order in filteredOrders" :key="order.id" class="order-item">
				<view class="order-content">
					<view class="order-details">
						<text class="order-title">{{ order.productName }}</text>
						<text class="order-info">成人 ¥{{ order.adultPrice }} x{{ order.adultCount }}，老人/学生
							¥{{ order.oldStuPrice }} x{{ order.oldStuCount }}</text>
						<text class="order-info">提交人：{{ order.userName }}</text>
						<text class="order-info">{{order.state ==='待出行'?'出行时间:':'创建时间:'}}{{formatAddTime(order.state,order.addTime)}}</text>
						<view class="divider"></view>
						<view class="order-status">
							<text :class="statusText(order.state)" class="status-text">{{order.state}}</text>
							<text class="order-action"
								@click="navigateTo(order.state,order.id)">{{ actionText(order.state) }}</text>
						</view>
					</view>
					<image class="order-image" :src="order.imgUrl" mode="aspectFill" />
				</view>
			</view>
		</scroll-view>
		<tabBarVue :current="current"></tabBarVue>
	</view>
</template>

<script>
	import tabBarVue from '../../../components/tabbar/tabbar.vue';
	import {
		getOrdersById
	} from '../../../api/user.js'
	import {
		mapState
	} from 'pinia'
	import {
		useUserInfoStore
	} from '../../../stores/userInfo.js'
	export default {
		data() {
			return {
				activeTab: '全部',
				current: 1,
				orders: [],
				order1: [],
				order2: []
			};
		},
		components: {
			tabBarVue
		},
		onShow() {
			uni.hideTabBar({
				animation: false
			})
			this.current = 1 // 公告页面和我的页面根据需要传入对应的索引号
		},
		onLoad() {
			this.getOrdersById()
		},
		onShow() {
			this.getOrdersById()
		},
		created() {
			this.getOrdersById()
		},
		computed: {
			...mapState(useUserInfoStore, ['userId', 'phone', 'username', 'state']),
			filteredOrders() {
				if(this.activeTab==='全部'){
				  return this.orders
				}else{
					return this.orders.filter(order => order.state === this.activeTab);
				}
				
			}
		},
		methods: {
			// 添加一个方法来格式化日期并加一天
			  formatAddTime(state,addTime) {
			    // 1. 将字符串转换为Date对象
			      const date = new Date(addTime.replace(/-/g, '/')); // iOS兼容处理
			      if(state ==='待出行'){
					  // 2. 加一天
					  date.setDate(date.getDate() + 1);
			      }
			      // 3. 格式化为YYYY-MM-DD HH:mm:ss
			      const year = date.getFullYear();
			      const month = String(date.getMonth() + 1).padStart(2, '0');
			      const day = String(date.getDate()).padStart(2, '0');
			      const hours = String(date.getHours()).padStart(2, '0');
			      const minutes = String(date.getMinutes()).padStart(2, '0');
			      const seconds = String(date.getSeconds()).padStart(2, '0');
			      
			      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			  },
			async getOrdersById() {
			  try {
			    if(!this.userId) {
			      this.orders = []; // 未登录时清空订单
			      return;
			    }
			    
			    // 并行获取两种订单
			    const [touristRes, agentRes] = await Promise.all([
			      getOrdersById('tourist', this.userId),
			      this.state ? getOrdersById('agent', this.userId) : Promise.resolve({data: []})
			    ]);
			    
			    this.order1 = touristRes.data || [];
			    this.order2 = (agentRes && agentRes.data) || [];
			    
			    // 合并订单并过滤无效数据
			    this.orders = [...this.order1, ...this.order2].filter(Boolean);
			    
			  } catch (error) {
			    console.error('获取订单失败:', error);
			    uni.showToast({ title: '获取订单失败', icon: 'none' });
			    this.orders = [];
			  } finally {
					this.loading = false;
				}
			},
			setActiveTab(tab) {
				this.activeTab = tab;
			},
			statusText(status) {
				switch (status) {
					case '全部':
						return 'all';
					case '待签署':
						return 'signed';
					case '待支付':
						return 'paid';
					case '待出行':
						return 'ready';
					case '已完成':
						return 'completed';
					default:
						return '';
				}
			},
			//&& this.orders.agentId === this.userId
			actionText(status) {
				switch (status) {
					case '待签署':
						return '签署合同';
					case '待支付':
						return '支付订单';
					case '待出行':
						return '查看合同';
					case '已完成':
						return '查看合同';
					default:
						return '';
				}
			},
			navigateTo(page, oid) {
				switch (page) {
					case '全部':
						uni.navigateTo({
							url:'/common/pages/order/order?tab=' + '全部'
						})
						//查看合同
					case '待支付':
							uni.navigateTo({
								url: '/pages/user/PendingPayment/pay?orderId=' + oid
							});
						break;
					case '待出行':
						uni.navigateTo({
							url: '/pages/user/contract/viewContract?orderId=' + oid
						});
						break;
					case '已完成':
						uni.navigateTo({
							url: '/pages/user/contract/viewContract?orderId=' + oid
						});
						break;
						//签署合同
					case '待签署':
						uni.navigateTo({
							url: '/pages/user/contract/viewContract?state=1&orderId=' + oid
						});
						break;
					default:
						console.warn('Unknown page:', page);
				}
			}
			
		}
	};
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.left-icon {
		position: absolute;
		left: 20px;
	}

	.right-icon {
		position: absolute;
		right: 20px;
	}

	.tabs {
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 10px 0;
	}

	.tab {
		font-size: 16px;
		color: #666;
		padding: 5px 0;
	}

	.tab.active {
		color: #007bff;
		border-bottom: 2px solid #007bff;
		font-weight: bold;
	}

	.order-list {
		flex: 1;
		width: 95%;
		padding: 10px;
	}

	.order-item {
		background-color: #fff;
		border-radius: 10px;
		margin-bottom: 10px;
		padding: 10px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 增强阴影效果 */
		transition: transform 0.2s, box-shadow 0.2s; /* 添加过渡效果 */
	}

	.order-item:last-child {
		margin-bottom: 100px;
	}
	
	/* 可选：添加悬停效果 */
	.order-item:hover {
	    transform: translateY(-2px); /* 轻微上浮 */
	    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15); /* 悬停时阴影更大 */
	}

	.order-content {
		display: flex;
		justify-content: space-between;
	}

	.order-image {
		width: 120px;
		height: 80px;
		right: 12px;
		border-radius: 8px;
	}

	.order-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-right: 10px;
	}

	.order-title {
		font-size: 14px;
		color: #333;
		margin-bottom: 5px;
	}

	.order-info {
		font-size: 12px;
		color: #666;
		margin-bottom: 5px;
	}

	.divider {
		height: 1px;
		background-color: #e0e0e0;
		margin: 5px 0;
	}

	.order-status {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		margin-top: 5px;
	}

	.confirmed {
		color: #1989fa;
	}

	.signed {
		color: #07c160;
	}

	.paid {
		color: #ee0a24;
	}

	.ready {
		color: orange;
	}

	.completed {
		color: gray;
	}

	/* 	.status-text {
		color: #007bff;
	} */

	.order-action {
		margin-right: -110px;
		font-size: 14px;
		color: #007bff;
	}

	.footer-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #888;
	}

	.footer-item.active {
		color: #1989fa;
	}

	.footer-icon {
		width: 24px;
		height: 24px;
		margin-bottom: 2px;
	}

	.footer-icon.active {
		filter: invert(45%) sepia(80%) saturate(1000%) hue-rotate(190deg) brightness(100%) contrast(95%);
	}
</style>